package com.atguigu.schedule.controller;

import com.atguigu.schedule.pojo.FaceDetectionResult;
import com.atguigu.schedule.pojo.PersonTrackingResult;
import com.atguigu.schedule.common.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 人脸识别和行人跟踪控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/face-tracking")
@RequiredArgsConstructor
public class FaceTrackingController {
    
    private final com.atguigu.schedule.service.FaceTrackingService faceTrackingService;
    
    /**
     * 检测图像中的人脸
     */
    @PostMapping("/detect-faces")
    public Result<List<FaceDetectionResult>> detectFaces(@RequestParam("image") MultipartFile image) {
        try {
            if (image.isEmpty()) {
                return Result.build(null, 400, "图像文件不能为空");
            }
            
            byte[] imageData = image.getBytes();
            List<FaceDetectionResult> results = faceTrackingService.detectFaces(imageData);
            
            return Result.ok(results);
            
        } catch (Exception e) {
            log.error("人脸检测失败", e);
            return Result.build(null, 500, "人脸检测失败: " + e.getMessage());
        }
    }
    
    /**
     * 检测图像中的行人
     */
    @PostMapping("/detect-persons")
    public Result<List<PersonTrackingResult>> detectPersons(@RequestParam("image") MultipartFile image) {
        try {
            if (image.isEmpty()) {
                return Result.build(null, 400, "图像文件不能为空");
            }
            
            byte[] imageData = image.getBytes();
            List<PersonTrackingResult> results = faceTrackingService.detectPersons(imageData);
            
            return Result.ok(results);
            
        } catch (Exception e) {
            log.error("行人检测失败", e);
            return Result.build(null, 500, "行人检测失败: " + e.getMessage());
        }
    }
    
    /**
     * 识别指定人脸
     */
    @PostMapping("/recognize-face")
    public Result<String> recognizeFace(@RequestParam("image") MultipartFile image) {
        try {
            if (image.isEmpty()) {
                return Result.build(null, 400, "图像文件不能为空");
            }
            
            byte[] imageData = image.getBytes();
            String name = faceTrackingService.recognizeFace(imageData);
            
            return Result.ok(name);
            
        } catch (Exception e) {
            log.error("人脸识别失败", e);
            return Result.build(null, 500, "人脸识别失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加新的人脸样本
     */
    @PostMapping("/add-face-sample")
    public Result<String> addFaceSample(@RequestParam("name") String name,
                                       @RequestParam("image") MultipartFile image) {
        try {
            if (name == null || name.trim().isEmpty()) {
                return Result.build(null, 400, "人员姓名不能为空");
            }
            
            if (image.isEmpty()) {
                return Result.build(null, 400, "图像文件不能为空");
            }
            
            byte[] imageData = image.getBytes();
            boolean success = faceTrackingService.addFaceSample(name.trim(), imageData);
            
            if (success) {
                return Result.ok("人脸样本添加成功");
            } else {
                return Result.build(null, 500, "人脸样本添加失败");
            }
            
        } catch (Exception e) {
            log.error("添加人脸样本失败", e);
            return Result.build(null, 500, "添加人脸样本失败: " + e.getMessage());
        }
    }
    
    /**
     * 训练人脸识别模型
     */
    @PostMapping("/train-model")
    public Result<String> trainModel() {
        try {
            boolean success = faceTrackingService.trainFaceModel();
            
            if (success) {
                return Result.ok("人脸识别模型训练成功");
            } else {
                return Result.build(null, 500, "人脸识别模型训练失败");
            }
            
        } catch (Exception e) {
            log.error("训练人脸识别模型失败", e);
            return Result.build(null, 500, "训练人脸识别模型失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有已注册的人脸信息
     */
    @GetMapping("/registered-faces")
    public Result<List<String>> getRegisteredFaces() {
        try {
            List<String> faces = faceTrackingService.getRegisteredFaces();
            return Result.ok(faces);
            
        } catch (Exception e) {
            log.error("获取已注册人脸失败", e);
            return Result.build(null, 500, "获取已注册人脸失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除指定人员的人脸数据
     */
    @DeleteMapping("/delete-face/{name}")
    public Result<String> deleteFaceData(@PathVariable String name) {
        try {
            if (name == null || name.trim().isEmpty()) {
                return Result.build(null, 400, "人员姓名不能为空");
            }
            
            boolean success = faceTrackingService.deleteFaceData(name.trim());
            
            if (success) {
                return Result.ok("人脸数据删除成功");
            } else {
                return Result.build(null, 404, "未找到指定人员的人脸数据");
            }
            
        } catch (Exception e) {
            log.error("删除人脸数据失败", e);
            return Result.build(null, 500, "删除人脸数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取人脸识别服务状态
     */
    @GetMapping("/status")
    public Result<Object> getStatus() {
        try {
            List<String> registeredFaces = faceTrackingService.getRegisteredFaces();
            
            Map<String, Object> status = new HashMap<>();
            status.put("serviceAvailable", true);
            status.put("registeredFaceCount", registeredFaces.size());
            status.put("registeredFaces", registeredFaces);
            status.put("detectedFaces", 0); // 实时检测的人脸数量
            status.put("detectedPersons", 0); // 实时检测的行人数量
            status.put("recentRecognitions", new ArrayList<>()); // 最近的识别结果
            
            return Result.ok(status);
            
        } catch (Exception e) {
            log.error("获取服务状态失败", e);
            return Result.build(null, 500, "获取服务状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 切换人脸识别服务状态
     */
    @PostMapping("/toggle-service")
    public Result<Object> toggleService(@RequestBody Map<String, Object> request) {
        try {
            Boolean enabled = (Boolean) request.get("enabled");
            
            Map<String, Object> result = new HashMap<>();
            result.put("enabled", enabled);
            result.put("message", enabled ? "人脸识别服务已启用" : "人脸识别服务已禁用");
            
            return Result.ok(result);
            
        } catch (Exception e) {
            log.error("切换服务状态失败", e);
            return Result.build(null, 500, "切换服务状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 开始实时检测
     */
    @PostMapping("/start-detection")
    public Result<String> startDetection() {
        try {
            // 这里可以添加实际的检测逻辑
            return Result.ok("实时检测已开始");
            
        } catch (Exception e) {
            log.error("开始检测失败", e);
            return Result.build(null, 500, "开始检测失败: " + e.getMessage());
        }
    }
    
    /**
     * 停止实时检测
     */
    @PostMapping("/stop-detection")
    public Result<String> stopDetection() {
        try {
            // 这里可以添加实际的停止检测逻辑
            return Result.ok("实时检测已停止");
            
        } catch (Exception e) {
            log.error("停止检测失败", e);
            return Result.build(null, 500, "停止检测失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取检测统计信息
     */
    @GetMapping("/detection-stats")
    public Result<Object> getDetectionStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            stats.put("detectedFaces", 0); // 当前检测到的人脸数量
            stats.put("detectedPersons", 0); // 当前检测到的行人数量
            
            return Result.ok(stats);
            
        } catch (Exception e) {
            log.error("获取检测统计失败", e);
            return Result.build(null, 500, "获取检测统计失败: " + e.getMessage());
        }
    }
}
